package orm

import (
	"github.com/Unixeno/TheMoon/logging"
	"github.com/Unixeno/TheMoon/planet/orm/model"
	"github.com/Unixeno/TheMoon/planet/orm/statistics"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

var logger = logging.GetLogger("orm")
var DB *gorm.DB

func Init() error {
	db, err := gorm.Open("sqlite3", "planet.db")
	if err != nil {
		logger.Fatal("failed to connect database")
		return err
	}
	DB = db
	initTables()
	return nil
}

func initTables() {
	DB.AutoMigrate(model.Moon{})
	DB.AutoMigrate(model.MoonInfo{})
	DB.AutoMigrate(model.Zone{})
	DB.AutoMigrate(model.ZoneMoon{})
	DB.AutoMigrate(model.Zonefile{})
	DB.AutoMigrate(model.Event{})

	err := statistics.Init()
	if err != nil {
		logger.WithError(err).Fatal("failed to initialize influxdb")
	}
}

func Shutdown() {
	DB.Close()
}
